import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { TimeConfigClass } from '../../../common/common-config';
import { StorageService } from "app/common/storage.service";
import { UsermanageService } from './usermanage.service';

@Component({
  selector: 'app-usermanage',
  templateUrl: './usermanage.component.html',
  styleUrls: ['./usermanage.component.css'],
  providers: [UsermanageService]
})
export class UsermanageComponent implements OnInit {

  timeConfig: any = new TimeConfigClass(); // 时间空间初始化
  loading: boolean = true;
  colsSelected: any;
  cols: any = [];
  selectedItem: any = []; //选中记录
  pageSize: number; // 每页条数
  pageNo: number; // 当前页
  listData: any = []; // 数据
  totalRecords: number; // 数据条数
  searchObj: any = {}; // 搜索条件
  searcSortObj: any = {}; // 排序信息
  selectedObj: any = {}; //选中条件

  sexArr: any = [];  //性别 表单
  sexSerchArr: any = [];  //性别 搜索
  portraitArr: any = [];//头像
  addressProvinceArr: any = []; //地区—省
  addressCityArr: any = []; //地区-市
  addressAreaArr: any = []; //地区-区
  favoriteStyleArr: any = [];  //喜欢的风格
  sourceArr: any = [];  //来源
  statusArr: any = [];  //状态

  //高级搜索
  isShowH: boolean = false; //弹窗H
  searchHighObj: any = {}; // 高级搜索
  selectedHighObj: any = {}; //选中条件

  //支付记录
  isShowP: boolean = false; //弹窗p
  paymentList: any = [];

  //form
  isShow: boolean = false; //弹窗a
  isEdit: boolean = false;
  dateKey: string = '';//数据标识
  baseObj: any = {};//原始数据
  formObj: any = {};//提交数据
  formOptObj: any = {};//表单选中数据
  errorObj: any = {};//错误信息


  constructor(private storage: StorageService, private router: Router, private server: UsermanageService) {
    // console.log('constructor');
    this.cols = [
      { field: 'code', header: '用户ID', frozen: false, sortable: true, tem: true, width: '10%' },
      { field: 'phoneNumber', header: '手机号', sortable: true, width: '10%' },
      { field: 'name', header: '姓名', frozen: false, sortable: true, width: '10%' },
      { field: 'portraitPath', header: '头像', tem: true, width: '6%' },
      { field: 'nickname', header: '昵称', sortable: true , width: '10%'},
      { field: 'sexDic', header: '性别', sortable: true, width: '8%' },
      { field: 'birthday', header: '生日', sortable: true, width: '8%' },
      // { field: 'sourceDic', header: '来源', sortable: true, width: '80px' },
      { field: 'addressChinese', header: '地区', sortable: true , width: '12%'},
      { field: 'addressDetail', header: '常住地址', sortable: true , width: '12%'},
      { field: 'registerTime', header: '注册时间', sortable: true, width: '8%' },
      // { field: 'favoriteStyleDic', header: '喜欢的风格', sortable: true },
      { field: 'isEffect', header: '状态', sortable: true, tem: true, width: '8%' }
    ];
    this.colsSelected = this.cols;

  }

  ngOnInit() {
    //console.log('ngOnInit',this.selectedObj.insuranceEndTimeMinDate);
    this.getDictionaries();
  }


  //禁用
  stopUsing() {
    let list = this.selectedItem;
    if (list.length < 1) {
      this.warning2();
      return false;
    }
    let ids = [];
    for (let index in list) {
      ids.push(list[index].code)
    }
    this.storage.makesureService.emit({
      message: '确定要禁用您选定的' + list.length + '项吗?',
      header: '提示',
      icon: 'fa fa-question-circle',
      accept: () => {
        this.loading = true;
        this.server.stopUsing(ids.join(",")).then(
          data => {
            this.loading = false;
            if (data.result) {
              const params = Object.assign(this.searchObj, this.searchHighObj,this.searcSortObj);
              this.getData(params);
              this.success();
              this.selectedItem = [];
              console.log('修改成功!');
            } else {
              this.error();
              console.log('后台错误！');
            }
          }
        );
      },
      reject: () => { }
    });
  }

  //启用
  startUsing() {
    let list = this.selectedItem;
    if (list.length < 1) {
      this.warning2();
      return false;
    }
    let ids = [];
    for (let index in list) {
      ids.push(list[index].code)
    }
    this.storage.makesureService.emit({
      message: '确定要启用您选定的' + list.length + '项吗?',
      header: '提示',
      icon: 'fa fa-question-circle',
      accept: () => {
        this.loading = true;
        this.server.startUsing(ids.join(",")).then(
          data => {
            this.loading = false;
            if (data.result) {
              const params = Object.assign(this.searchObj, this.searchHighObj,this.searcSortObj);
              this.getData(params);
              this.success();
              this.selectedItem = [];
              console.log('修改成功!');
            } else {
              this.error();
              console.log('后台错误！');
            }
          }
        );
      },
      reject: () => { }
    });

  }

  /**
   * 获取数据
   */
  getData(params) {
    //let params = this.searchObj;
    this.loading = true;
    this.server.list(params, this.pageSize, this.pageNo).then(
      data => {
        this.loading = false;
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
          this.refreshObjToPost();
        } else {
          this.listData = [];
          this.totalRecords = 0;
          console.log('后台错误！');
        }
      }
    );

  }
  /**
   * 改变模糊搜索框数据值
   */
  searchTextChange(event){
    if(event==undefined)
      return false
    if(event.constructor==String && event!=''){
      this.searchObj['searchValue'] = event;
    }else{
      this.searchObj['searchValue'] = undefined;
    };
  }
  /**
   * 搜索方法
   * @param event
   */
  search(event?) {
    //筛选查询
    this.searchTextChange(event);
    // this.pageNo = 1;
    this.searchHighObj = {};
    const params = Object.assign(this.searchObj);
    this.getData(params);
  }
  /**
   * 搜索方法 高级
   */
  searchHigh() {

    if(this.searchHighObj.registerTimeBegin==undefined&&this.searchHighObj.registerTimeEnd!=undefined){
      this.warning2('请选择开始时间');
      return false;
    } else if(this.searchHighObj.registerTimeBegin!=undefined&&this.searchHighObj.registerTimeEnd==undefined){
      this.warning2('请选择结束时间');
      return false;
    }
    this.searchObj = {};
    const params = Object.assign(this.searchHighObj);
    this.getData(params);
    this.isShowH = false;
  }
  /**
   * 分页查询
   * @param event
   */
  loadCarsLazy(event) {
    this.pageSize = + event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    this.searcSortObj['sortF'] = event.sortField;
    this.searcSortObj['sortO'] = event.sortOrder == 1 ? 'asc' : 'desc';
    const params = Object.assign(this.searchObj, this.searchHighObj, this.searcSortObj);
    this.getData(params);
  }

  /**
  * 加载字典项
  */
  getDictionaries() {
    // 加载工种和工人状态
    this.server.getDictionaries().then(
      data => {
        if (data.result) {
          //性别
          this.sexArr = data.data.sex;
          //性别 搜索
          this.sexSerchArr = Object.assign([], data.data.sex);
          this.sexSerchArr.unshift( {code: '', name: '全部'});
          //地区
          this.addressProvinceArr = data.data.district.province;
          //风格
          this.favoriteStyleArr = data.data.favoriteStyle;
          this.favoriteStyleArr.unshift( {code: '', name: '请选择'});
          //来源
          this.sourceArr =  data.data.source;
          this.sourceArr.unshift( {code: '', name: '全部'});

          //状态
          this.statusArr = [{code: '', name: '请选择'},{code:"true",name:"已启用"},{code:"false",name:"已禁用"}];
        } else {
        }
      }
    );
  }
  //地址改变
  addressChange(val) {
    if (val == 'province') {
      this.addressCityArr = this.selectedObj.addressProvince.city;
      this.addressAreaArr = [];
    } else if (val == 'city') {
      this.addressAreaArr = this.selectedObj.addressCity.area;
    }
  }

  /**
   * 改变时间
   */
  calendarChangeHigh(e){
    this.selectedHighObj[e] = new Date(this.searchHighObj[e]);
  }

  /*********表单***********/

  /**
   * 重置表单数据
   */
  resetFormDate() {
    this.isShow = false; //弹窗a
    this.isEdit= false;
    this.baseObj = {};//原始数据
    this.formObj = {};
    this.formOptObj = {};
    this.selectedObj = {};
    this.errorObj = {};//错误信息
  }
  /**
   * 编辑
   */
  edit(code) {
    if(code==undefined){
      this.error();
      return false;
    };
    this.resetFormDate();
    this.dateKey = code;
    this.getFormData(this.dateKey);
  }

  /**
   * 获取数据
   */
  getFormData(code) {
    this.server.get(code).then(data => {
      this.loading = false;
      if (data.result) {
        this.formObj = data.data;
        this.baseObj = Object.assign({},data.data);
        //地区
        this.selectedObj.addressProvince = (this.addressProvinceArr.filter(item => item.area_code == this.formObj.addressProvince))[0];
        this.addressCityArr = this.selectedObj.addressProvince.city;
        this.selectedObj.addressCity = (this.addressCityArr.filter(item => item.area_code == this.formObj.addressCity))[0];
        this.addressAreaArr = this.selectedObj.addressCity.area;
        this.selectedObj.addressArea = (this.addressAreaArr.filter(item => item.area_code == this.formObj.addressArea))[0];
        this.isShow = true;
      } else {
        this.error();
      }
    });
  }

  /**
   * 保存
   */
  save() {
    //自定义验证
    let params = this.formObj
    if (this.selectedObj.addressProvince) {
      params['addressProvince'] = this.selectedObj.addressProvince.area_code;
    }
    if (this.selectedObj.addressCity) {
      params['addressCity'] = this.selectedObj.addressCity.area_code;
    }
    if (this.selectedObj.addressArea) {
      params['addressArea'] = this.selectedObj.addressArea.area_code;
    }
    this.loading = true;
    this.server.save(params).then(data => {
      this.loading = false;
      if (data.result) {
        this.getFormData(this.dateKey);
        this.isEdit=false;
      } else {
        this.error('操作失败');
      }
    });
  }
  /**
   * 更新数据
   */
  refreshObjToPost() {
    const code = this.formObj['code'];
    if (code != undefined) {
      this.formObj = (this.listData.filter(item => item.code == code))[0];
    }
  }

  /**
   * 手机号唯一验证
   * @param data
   */
  uniqueFTelephone(obj) {
    if (obj.errors != null) {
      return false;
    }
    let phoneNumber = this.formObj.phoneNumber
    if (this.baseObj.phoneNumber == phoneNumber) {
      return false;
    }
    // this.errorObj.phoneNumber['way'] = true;
    this.server.checkUserIsExistByPhoneNumber(phoneNumber).then(data => {
        if (data.result) {
            this.errorObj.phoneNumber['exist'] = true;
        } else {
          this.errorObj.phoneNumber['exist'] = false;
        };
        // this.errorObj.phoneNumber['way'] = false;
    });
    //等待15秒  超时
    // setTimeout(() => {
    //   if (this.phoneNumberCase == 2) { this.phoneNumberCase = 3; }
    // }, 15000);
  }

  /**
   * 自定义验证
   */
  verifyCustom(){

    return true;
  }
  /**
   * 验证字段信息显示
   */
  verifyFields(e,obj){
    if(e==undefined || e['name']==undefined || obj==undefined){
      return false;
    };
    let err = {show:true};
    if(e['value']==undefined || e.value.trim()==''){
      err['blank'] = true;
    };
    this.errorObj[e.name] = err;
    obj[e.name] = e['value'] == undefined ? '' : e.value.trim();
  }
  /**
   * 清除验证信息提示框
   */
  clearVerify(e){
    if(e==undefined){
      return false;
    }
    this.errorObj[e.name] = {show:false};
  }
  /*********支付记录***********/
  /**
   * 支付记录
   */
  openPayment() {
    let list = this.selectedItem;
    if (list.length == 0) {
      this.warning2();
      return false;
    }
    if (list.length > 1) {
      this.warning2('只能勾选一条数据！');
      return false;
    }
    let ids = [];
    for (let index in list) {
      ids.push(list[index].code)
    }
    this.loading = true;
    this.server.paymentListByCode(ids.join(",")).then(
      data => {
        this.loading = false;
        if (data.result) {
          this.paymentList = data.data;
          this.isShowP = true;
          this.selectedItem = [];
        } else {
          this.error();
        }
      }
    );

  }

  /**
   * 提示框
   */
  success(msg? : string) {
    msg = msg!=undefined ? msg : '操作成功';
    this.storage.messageService.emit({ severity: 'success', detail: msg });
  }
  error(msg? : string) {
    msg = msg!=undefined ? msg : '请选择要操作的数据！';
    this.storage.messageService.emit({ severity: 'error', detail: msg });
  }
  warning(msg? : string) {
    msg = msg!=undefined ? msg : '请选择要操作的数据！';
    this.storage.messageService.emit({ severity: 'warn', detail: msg });
  }
  warning2(msg? : string) {
    msg = msg!=undefined ? msg : '请选择要操作的数据！';
    this.storage.makesureService.emit({
      message: msg,
      header: '提示',
      icon: '',
      rejectVisible:false,
      accept: () => { },
      reject: () => { }
    });
  }




}
